<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>eventBus练习</title>
</head>
<body>
    <div id="app">
        <bro1></bro1>
        <bro2></bro2>
    </div>
</body>
</html>

<template id="bro1">
    <fieldset>
        <legend>bro1</legend>
        <input type="text" v-model="val">
        <button @click="add">添加</button>
    </fieldset>
</template>
<template id="bro2">
    <fieldset>
        <legend>bro2</legend>
        <ul>
            <li v-for="(item,index) in arr" :key="index">{{item}}</li>
        </ul>
    </fieldset>
</template>

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script>
    
    //1.设置eventBus
    //2.要触发事件的元素(有添加操作的)，要定义方法add，里面写eventBus.$emit("起个名",this.val)
    //3.兄弟2用来接收的里面，设置钩子函数mounted(){里面注册事件eventBus.$on("名",input=>{push})}
    //4.注意兄弟2的注册事件，要用箭头函数，不然this指向会出问题
    
    var eventBus = new Vue()   // 设置eventBus 

    Vue.component("bro1",{
        template:"#bro1",
        data(){
            return {
                val:""
            }
        },
        methods: {
            add(){
                eventBus.$emit("add",this.val)
                this.val = ""
            }
        }
    }),
    Vue.component("bro2",{
        template:"#bro2",
        data(){
            return {
                arr:["11","22","33"]
            }
        },
        mounted () {   // 钩子函数
            eventBus.$on("add",(input)=>{
                console.log(this);
                this.arr.push(input)
            })
        }
    })
    let vm = new Vue({
        el: "#app"
    })
</script>